package org.ourgrid.peer.ui.async;

import java.awt.image.BufferedImage;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;

import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

import org.ourgrid.peer.PeerComponentContextFactory;
import org.ourgrid.peer.PeerConfiguration;
import org.ourgrid.peer.ui.async.client.PeerAsyncApplicationClient;
import org.ourgrid.peer.ui.async.client.PeerAsyncInitializer;
import org.ourgrid.peer.ui.async.gui.PeerGUIMainFrame;
import org.ourgrid.peer.ui.async.model.PeerAsyncUIModel;

import br.edu.ufcg.lsd.commune.context.ModuleContext;
import br.edu.ufcg.lsd.commune.context.PropertiesFileParser;

public class GridMain extends Thread{

	private static final String PEERGUI_PROPERTIES = "peer.properties";
	
	public void run(){
		try {
    		UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (InstantiationException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (UnsupportedLookAndFeelException e) {
			e.printStackTrace();
		}
		
		PeerAsyncUIModel model = new PeerAsyncUIModel();
		model.loadProperties();
		PeerAsyncInitializer.getInstance().setModel(model);
		
		BufferedImage iconImage = null;
		
		try {
			iconImage = ImageIO.read(GridMain.class.getResourceAsStream("/resources/images/icon.png"));
		} catch (IOException e1) {
			System.out.println(e1.getMessage());
		}
		
		final PeerGUIMainFrame frame = new PeerGUIMainFrame(iconImage, model);
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.setVisible(true);
		model.addListener(frame);
		
		PeerAsyncApplicationClient componentClient = null;
		try {
			ModuleContext context = new PeerComponentContextFactory(
					new PropertiesFileParser(PEERGUI_PROPERTIES)).createContext();
			saveProperties(context);
			
			componentClient = PeerAsyncInitializer.getInstance().initComponentClient(context, model);
		} catch (Exception e) {
			JOptionPane.showMessageDialog(null, e.getMessage(), "Error on peer startup", JOptionPane.ERROR_MESSAGE);
			frame.peerStopped();
			frame.setStartEnabled(false);
			return;
		}
		
		if (componentClient.getModel().isPeerUp()) {
			frame.peerStarted();
		} else {
			frame.peerStopped();
		}
	}
	
	private static void saveProperties(ModuleContext context) throws FileNotFoundException, IOException {
		Properties properties = new Properties();
		properties.putAll(context.getProperties());
		properties.store(new FileOutputStream(PeerConfiguration.PROPERTIES_FILENAME), null);
	}
	
}
